// Resource Manager
// (c) jimon game studio

#include "CResourceManager.h"

namespace je
{
	namespace media
	{
		IMPLEMENT_SINGLETON(ResourceManager,JE_ENGINE_FUNCTION_CALL)

		//! Destructor
		CResourceManager::CResourceManager()
			:CurrentDataBase(NULL)
		{
			SetResourceManager(this);
		}

		//! Destructor
		CResourceManager::~CResourceManager()
		{
			GarbageCollector();

			SetDataBase(NULL);

			for(ResourceMapType::Iterator Iter = ResourceMap.getIterator();!Iter.atEnd();Iter++)
				Iter->getValue()->Drop();

			SetResourceManager(NULL);
		}

		//! Set DataBase
		void CResourceManager::SetDataBase(core::IDataBase * DataBase)
		{
			if(CurrentDataBase)
				CurrentDataBase->Drop();
			
			CurrentDataBase = DataBase;
			
			if(CurrentDataBase)
			{
				CurrentDataBase->Grab();
				for(ResourceMapType::Iterator Iter = ResourceMap.getIterator();!Iter.atEnd();Iter++)
					Iter->getValue()->LoadResources();
			}
		}

		//! Get Data Base
		core::IDataBase * CResourceManager::GetDataBase()
		{
			return CurrentDataBase;
		}

		//! Get Resource
		IResource * CResourceManager::GetResource(const jeStringc & ResourceType,const jeStringc & ResourceName)
		{
			return ResourceMap.find(ResourceType)->getValue()->GetResource(ResourceName);
		}

		//! Get Resource Factory
		IResourceFactory * CResourceManager::GetResourceFactory(const jeStringc & ResourceType)
		{
			return ResourceMap.find(ResourceType)->getValue();
		}

		//! Register Resource Factory
		void CResourceManager::RegisterResourceFactory(IResourceFactory * Factory)
		{
			ResourceMap.set(Factory->GetResourceType(),Factory);
			Factory->Grab();
		}

		//! Garbage Collector
		void CResourceManager::GarbageCollector()
		{
			for(ResourceMapType::Iterator Iter = ResourceMap.getIterator();!Iter.atEnd();Iter++)
				Iter->getValue()->GarbageCollector();
		}
	}
}
